const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    touchNode: cc.Node = null;

    @property
    height: number = 300;

    @property(cc.Button)
    startButton: cc.Button = null

    @property
    grivate: number = 1.3

    @property(cc.Animation)
    gameOverLabel: cc.Animation = null;

    @property(cc.Label)
    scoreLabel: cc.Label = null


    isGameStart:boolean = false
    isGameOver:boolean = false

    score:number = 0

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {
        //触摸事件
        this.touchNode.on(cc.Node.EventType.TOUCH_START,this.flying,this)
        //键盘事件
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN,this.flying,this)

        this.node.on("score",this.addScore,this)
    }

    // update (dt) {}

    flying(){
        if(!this.isGameStart){
           this.startGame() //调用游戏开始函数
        }
        if(this.isGameOver){
            return
        }
        if(this.node.y > cc.winSize.height/2){
            return //不允许飞出屏幕
        }
        let rigid = this.node.getComponent(cc.RigidBody) //获取刚体属性
        rigid.linearVelocity = cc.v2(0,this.height) //线性速度
    }

    startGame(){
        let rigid = this.node.getComponent(cc.RigidBody) //获取刚体属性
        rigid.gravityScale = 1.3
        this.startButton.clickEvents[0].emit([]) //手动激活事件
        this.startButton.node.active = false //把点击事件禁用
        cc.PhysicsBoxCollider
    }

    gameOver(){
        this.gameOverLabel.node.active = true
        this.gameOverLabel.play()

        this.isGameOver = true

        let rigid = this.node.getComponent(cc.RigidBody) //获取刚体属性
        rigid.angularVelocity = -360 //角速度

        let anim = this.node.getComponent(cc.Animation)
        anim.stop()

        //该函数只执行一次
        this.scheduleOnce(() => {
            cc.director.loadScene("像素鸟")
        },5)
    }

    addScore(){
        this.score++
        this.scoreLabel.string = this.score.toString()
    }

    onBeginContact(contact:cc.PhysicsContact,selfCollider:cc.PhysicsCollider,otherCollider:cc.PhysicsCollider){
        cc.log("撞到了")
        if(this.isGameOver){
            return
        }
        this.gameOver()
    }
}
